import { GenericEnvStore } from "@/modules/dev-env/store/generic-env-store.ts";
import type { JdkVersionInfo } from "./types.ts";
import path from "@/framework/util/path.ts";
import { JdkReleaseFile } from "./jdk-release-file.ts";
import type { BaseEnvMirror } from "@/modules/dev-env/mirror/mirror.ts";
import type { EnvTableAction, EnvVariableConfig } from "@/modules/dev-env/store/types.ts";
import { JdkLibericaMirror } from "./liberica-mirror.ts";
import { compareJdkVersion } from "./jdk-utils.ts";
import { execInTerminal, openInTerminal } from "@/util/system-utils2.ts";
import { DragonwellJdkMirror } from "./dragonwell-mirror.ts";
import { GraalVMNanjinguMirror } from "./graalvm-nanjingu-mirror.ts";
import type { LocalVersionItem } from "@/modules/dev-env/common/types.ts";
import { message } from "ant-design-vue";
import { EnvTree } from "@/modules/dev-env/common/tree.ts";

/**
 * JDK环境管理
 */
export class JdkEnvStore extends GenericEnvStore<JdkEnvStore, JdkVersionInfo> {
  constructor() {
    super("java", 2);

    this.icon = "icon-java";
    this.tableColumns = [{ dataIndex: "versionDate", title: "发布日期", width: "140px", align: "center" }];
    this.tableActions = this._tableActions();
  }

  private _tableActions(): EnvTableAction[] {
    return [
      {
        key: "open-in-terminal",
        name: "在终端打开",
        icon: "icon-terminal",
        onClick: record => openInTerminal(record.installPath, { subPath: ["bin"], env: this._getJavaEnv(record) }),
      },
      {
        key: "open-jshell",
        name: "JShell",
        icon: "icon-terminal",
        onClick: record => this._openJShell(record),
      },
    ];
  }

  private _getJavaEnv(record: LocalVersionItem) {
    return {
      JAVA_HOME: record.installPath,
      CLASSPATH: [".", path.join(record.installPath, "lib")].join(path.delimiter),
    };
  }

  private async _openJShell(record: LocalVersionItem) {
    const jshellExeFile = path.join(record.installPath, "bin/jshell.exe");
    if (await native.fs.exists(jshellExeFile)) {
      execInTerminal(jshellExeFile, { cwd: record.installPath, subPath: ["bin"], env: this._getJavaEnv(record) });
    } else {
      message.error("版本不支持JShell");
    }
  }

  protected async getVersionInfo(versionDir: string): Promise<JdkVersionInfo | undefined> {
    const javaExeFile = path.join(versionDir, "bin/java.exe");
    const releaseFilePath = path.join(versionDir, "release");
    try {
      // 判断java.exe和release文件都存在
      if (!(await native.fs.exists(javaExeFile)) || !(await native.fs.exists(releaseFilePath))) {
        return;
      }

      const releaseFile = new JdkReleaseFile(releaseFilePath);
      await releaseFile.load();
      return {
        path: versionDir,
        installPath: versionDir,
        version: releaseFile.get("JAVA_VERSION"),
        versionDate: releaseFile.get("JAVA_VERSION_DATE"),
        implementor: releaseFile.get("IMPLEMENTOR"),
        variant: releaseFile.get("JVM_VARIANT"),
      };
    } catch (e) {
      console.error("load jdk version info error", e);
    }
  }

  protected compareVersion(a: JdkVersionInfo, b: JdkVersionInfo): number {
    return compareJdkVersion(b.version, a.version);
  }

  getMirrors0(): BaseEnvMirror[] {
    return [new DragonwellJdkMirror(), new JdkLibericaMirror(), new GraalVMNanjinguMirror()];
  }

  getEnvVariables0(): EnvVariableConfig[] {
    return [
      {
        name: "JAVA_HOME",
        getValue: () => path.join(this.installDir, EnvTree.currentVersionDir),
        settable: true,
        readonly: true,
        showCurrent: true,
        help: "根据设置自动生成，不可修改",
      },
      {
        name: "CLASSPATH",
        getValue: () => [".", path.join("%JAVA_HOME%", "lib")].join(path.delimiter),
        settable: true,
        showCurrent: true,
      },
      {
        name: "PATH",
        getValue: () => path.join("%JAVA_HOME%", "bin"),
        settable: false,
        readonly: true,
        copyName: false,
      },
    ];
  }
}
